<?php
/**
 * tvb log category
 * 
 * @author William Hu <william.hu@achievo.com>
 * @version 1.0
 * @package TVBLog
 */
class TVB_Logger_Categroy
{
	private $_priorities = array();
	private $_label = DEFAULT_LABEL;
	
	public function __construct($label)
	{
		$this->_label = $label;
		require_once 'TVB/Logger/Level.php';
		$this->_priorities = TVB_Logger_Level::info();
	}
	
    /**
     * Undefined method handler allows a shortcut:
     *   $log->priorityName('message')
     *     instead of
     *   $log->log('message', TVBLog::PRIORITY_NAME)
     *
     * @param  string  $method  priority name
     * @param  string  $params  message to log
     * @return void
     * @throws  TVB_Logger_Exception
     */
    public function __call($method, $params)
    {
		$level = TVB_Logger_Config::get('level', $this->_label);
        $priority = strtoupper($method);
		if (in_array($method, $level)) {
		
			if (($priority = array_search($priority, $this->_priorities)) !== false) {
				self::log(array_shift($params), $priority);
			} else {
				/** @see  TVB_Logger_Exception */
				require_once 'TVB/Logger/Exception.php';
				throw new TVB_Logger_Exception('Bad log priority');
			}
		}
    }
	
    /**
     * Log a message at a priority
     *
     * @param  mix   $data   info to log
     * @param  integer  $priority  Priority of message
     * @return void
     * @throws TVB_Logger_Exception
     */
    public function log($data, $priority)
    {
        if (! isset($this->_priorities[$priority])) {
            /** @see TVB_Logger_Exception */
			require_once 'TVB/Logger/Exception.php';
            throw new TVB_Logger_Exception('Bad log priority');
        }

        // pack into event required by filters and writers
		require_once 'TVB/Logger/Entity.php';
		$log_entity = new TVB_Logger_Entity();
		$log_entity->when = date('D M j H:i:s Y');
		if(is_string($data)) {
			$log_entity->result 	= $data;
			$log_entity->who 		= DEFAULT_LABEL;
			$log_entity->request 	= '';
			$log_entity->note 		= '';
		} else if (array_key_exists('result', $data)) {
			$log_entity->result 	= $data['result'];
			$log_entity->who 		= isset($data['who'])?$data['who']:'root';
			$log_entity->request 	= isset($data['request'])?$data['request']:'';
			$log_entity->note 		= isset($data['note'])?$data['note']:'';
		} else {
			require_once 'TVB/Logger/Exception.php';
            throw new TVB_Logger_Exception('Bad data log entity');
		}
		$log_entity->level 		= strtolower($this->_priorities[$priority]);
		$log_entity->category 	= strtolower($this->_label);

        // send to each appender
		$appenders = TVB_Logger_Config::getAppender($this->_label);
        foreach ($appenders as $appender) {
            $appender->write($log_entity);
        }
		return true;
    }
}
?>